/*
	ByteBuffer class
	Written by
	Version 1.0

	buffering data chunk with any size

*/

// changed by [2/24/2017 Administrator]
#ifndef _BYTE_BUFFER_H_
#define _BYTE_BUFFER_H_


class ByteBuffer
{
public:
	ByteBuffer()	{
		m_pBuffer = NULL;
		m_nBufSize = 0;
	}
	
	~ByteBuffer(){
		Reset();
	};
	

	bool Init(int nBufInitSize, bool bAutoInc=false){
		if (nBufInitSize <= 0)
			return false;
		if (m_nBufSize >= nBufInitSize) {
			m_bAutoInc = bAutoInc;
			Clear();
			return true;
		}
		Reset();
		m_pBuffer = new char[nBufInitSize];
		if (!m_pBuffer)
			return false;
		m_nBufSize = nBufInitSize;
		m_bAutoInc = bAutoInc;
		Clear();
		return true;
	};

	void Reset(){
		Clear();
		if (m_pBuffer) {
			delete[] m_pBuffer;
			m_pBuffer = NULL;
		}
	};

	void Clear(){
		m_nBufPos = 0;
	};


	void SetAutoInc(bool bAutoInc) { m_bAutoInc = bAutoInc; }
	bool IsAutoInc() { return m_bAutoInc; }


	bool Feed(char *pData, int &nLen){ // changed by, here pBytes --> pData [2/27/2017 Administrator]
		if (!pData || nLen < 0 || !m_pBuffer)
			return false;
		int	nUsable = nLen;
		if (m_nBufPos+nLen > m_nBufSize)
			if (m_bAutoInc) {
				int	nNewSize = m_nBufSize * 3 / 2;
				char	*pNewBuf = new char[nNewSize];
				if (pNewBuf) {
					memcpy(pNewBuf, m_pBuffer, m_nBufPos);
					delete[] m_pBuffer;
					m_pBuffer = pNewBuf;
					m_nBufSize = nNewSize;
				}
				else
					return false;
			}
			else
				nUsable = m_nBufSize - m_nBufPos;
		memcpy(m_pBuffer+m_nBufPos, pData, nUsable);
		nLen -= nUsable;
		m_nBufPos += nUsable;
		return true;
	};
	char *GetBytes() { return m_pBuffer; }
	int GetByteNum() { return m_nBufPos; }
	int &ByteNum() { return m_nBufPos; }
	bool IsFull() { return (m_pBuffer && m_nBufPos == m_nBufSize); }
	bool Shift(int nLen){
		if (!m_pBuffer || nLen < 0)
			return false;
		if (nLen == 0)
			return true;
		else if (nLen >= m_nBufPos) {
			m_nBufPos = 0;
			return true;
		}
		memmove(m_pBuffer, m_pBuffer+nLen, m_nBufPos-nLen);
		m_nBufPos -= nLen;
		return true;
	};

private:
	char	*m_pBuffer;
	int		m_nBufSize;
	bool	m_bAutoInc;
	int		m_nBufPos;
};

#endif
